import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN } from '@/store/mutation-types';
import { AuthEnum, ResultEnum } from '@/enums/httpEnum';
import { useTabsViewStore } from '@/store/modules/tabsView';
import { useImChatStore } from "@/store/modules/imchat";

import { getUserInfo, login, logout } from '@/api/authority/user';
import { storage } from '@/utils/Storage';
import { PageEnum } from "@/enums/pageEnum";

export interface IUserState {
  token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: any;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): object {
      return this.info;
    },
    isAdmin(): boolean {
      return this.info?.id === 1
    }
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info) {
      this.info = info;
      this.username = info.username
      this.setAvatar(info.avatar)
      storage.set(CURRENT_USER, info)
    },
    // 登录
    async login(userInfo) {
      try {
        const response = await login(userInfo);
        const { code } = response.data;
        if (code === ResultEnum.SUCCESS) {
          let token = response['headers'][AuthEnum.AUTH_TOKEN_HEADER].split(" ")[1];
          storage.set(ACCESS_TOKEN, token);
          storage.set(IS_LOCKSCREEN, false);
          this.setToken(token);
        }
        return Promise.resolve(response.data);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 刷新用户信息
    async refreshUserInfo() {
      try {
        const result = await getUserInfo();
        this.setUserInfo(result);
        return Promise.resolve(result);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    GetInfo() {
      const that = this;
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(res => {
            const result = res;
            if (result.permissions && result.permissions.length) {
              const permissionsList = result.permissions;
              that.setPermissions(permissionsList);
              that.setUserInfo(result);
            } else {
              reject(new Error('getInfo: permissionsList must be a non-null array !'));
            }
            // socket启动器
            const { bootstrapSocket } = useImChatStore();
            bootstrapSocket().then(() => {});
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async logout() {
      // 关闭连接
      const { socketClose } = useImChatStore();
      socketClose();
      const { closeAllTabs } = useTabsViewStore();
      // 移除标签页
      closeAllTabs();
      window.setTimeout(async () => {
        await logout()
        storage.clear4Important();
        window['$message'].info('安全退出');
        window.location.replace(PageEnum.BASE_LOGIN);
      }, 100)
      return Promise.resolve('');
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
